package cn.edu.ctbu.scoremg.controller;

import cn.edu.ctbu.scoremg.constant.REnum;
import cn.edu.ctbu.scoremg.service.*;
import cn.edu.ctbu.scoremg.util.RUtil;
import cn.edu.ctbu.scoremg.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/auth")
public class AuthController {

    @Autowired
    private StudentService studentService;

    @Autowired
    private TeacherService teacherService;

    @Autowired
    private AdminService adminService;

    @PostMapping("/login")
    public R login(@RequestParam String no,
                   @RequestParam String password,
                   @RequestParam Integer roleType) {
        try {
            Object user = null;
            String role = null;

            // 验证用户
            switch(roleType) {
                case 1: // 学生
                    user = studentService.validateUsernameAndPassword(no, password);
                    role = "student";
                    break;
                case 2: // 教师
                    user = teacherService.validateNoAndPassword(no, password);
                    role = "teacher";
                    break;
                case 3: // 管理员
                    user = adminService.validateUsernameAndPassword(no, password);
                    role = "admin";
                    break;
                default:
                    return RUtil.error(REnum.LOGIN_ERR.getCode(), "无效的角色类型");
            }

            if(user == null) {
                return RUtil.error(REnum.LOGIN_ERR.getCode(), "账号或密码错误");
            }

            // 返回用户信息和角色
            Map<String, Object> data = new HashMap<>();
            data.put("user", user);
            data.put("role", role);

            return RUtil.success(data);
        } catch (Exception e) {
            return RUtil.error(REnum.LOGIN_ERR.getCode(), e.getMessage());
        }
    }
}